﻿
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
using System.Diagnostics;

namespace n_STlinkForm
{
	public partial class STlinkForm : Form
	{
		Process Proc;
		delegate void DelReadStdOutput(string result);
		event DelReadStdOutput ReadStdOutput;
		
		//构造函数
		public STlinkForm()
		{
			InitializeComponent();
			
			Proc = new Process();
			ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
			
			this.Visible = false;
		}
		
		//运行窗体
		public void Run()
		{
			//注意,直接设置Visible不能使窗体获得焦点
			this.Visible = true;
			
			while( this.Visible ) {
				System.Windows.Forms.Application.DoEvents();
			}
		}
		
		//确定键按下
		void ButtonOkClick(object sender, EventArgs e)
		{
			//先显示出来让用户关闭, 因为目前还不能自动关闭
			//Proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
			
			//Proc.StartInfo.UseShellExecute = false;
			//Proc.StartInfo.CreateNoWindow = true;
			//Proc.StartInfo.RedirectStandardOutput = true;
			
			//Proc.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
			//Proc.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
			
			
			Proc.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory + @"Resource\tools\ST-LINK Utility";
			
			Proc.StartInfo.FileName = @"ST-LINK_CLI.exe";//调用汇编命令
			
			string HexFile = @"Resource\remo-os\nucleo-f411re\Nucleo411.hex";
			
			Proc.StartInfo.Arguments = "-P \"" + (AppDomain.CurrentDomain.BaseDirectory + HexFile) + "\" -Rst -Run";
			
			Proc.Start();
		}
		
		void p_OutputDataReceived(object sender, DataReceivedEventArgs e)  
		{
			if (e.Data != null) {
				// 4. 异步调用，需要invoke
				this.Invoke(ReadStdOutput, new object[] { e.Data });
			}
		}
		
		void ReadStdOutputAction(string result)
		{
			this.textBoxShowStdRet.AppendText(result + "\n");
		}
		
		//窗口关闭
		void AVRdudeSetFormFormClosing(object sender, FormClosingEventArgs e)
		{
			this.Visible = false;
			e.Cancel = true;
		}
	}
}

